package org.proxywars.engine.rts.parties;

import java.util.ArrayList;
import java.util.List;

import org.proxywars.engine.rts.Framework;
import org.proxywars.engine.rts.IEvent;
import org.proxywars.engine.rts.IParty;
import org.proxywars.engine.rts.IUnit;
import org.proxywars.engine.rts.IUnitGroup;
import org.proxywars.engine.rts.events.UnitCreatedEvent;
import org.proxywars.engine.rts.units.UnitGroup;

public class AbstractParty implements IParty {

	private List<IUnit> units = new ArrayList<IUnit>();
	private List<IUnit> createdUnits = new ArrayList<IUnit>();

	@Override
	public void addUnit(IUnit unit) {
		units.add(unit);
		fireUnitAddedEvent(unit);
	}

	protected void fireUnitAddedEvent(IUnit unit) {
		// TODO How to send events (global events seen by all parties
		Framework.getInstance().sendGlobalEvent(new UnitCreatedEvent(unit));
	}

	@Override
	public void removeUnit(IUnit unit) {
		// FIXME units must be reomved from all groups too
		units.remove(unit);
	}

	@Override
	public IUnitGroup createGroup() {
		return new UnitGroup(this);
	}

	@Override
	public List<IUnit> getUnits() {
		return units;
	}

	@Override
	public void addCreatedUnit(IUnit unit) {
		createdUnits.add(unit);
	}

	@Override
	public void transferCreatedUnits() {
		for (IUnit unit : createdUnits)
			addUnit(unit);
		createdUnits.clear();
	}

	@Override
	public void handleEvent(IEvent event) {
		log(event);
		for (IUnit unit : getUnits())
			unit.handleEvent(event);
	}

	private void log(IEvent event) {
		Framework.getInstance().log(event);
	}
}
